﻿using System.Web.Mvc;
using Kratos.Framework.Extensions;

namespace Kratos.Framework.Filters
{
    public class AjaxAttribute : ActionFilterAttribute
    {
        private readonly HttpVerbs _httpVerbs;
        public AjaxAttribute(HttpVerbs httpVerbs = HttpVerbs.Post)
        {
            _httpVerbs = httpVerbs;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string actionName = filterContext.RequestContext.RouteData.Values["action"].ToString();
            if (!filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new ContentResult { Content = "方法 {0} 必须是Ajax请求才能访问!".With(actionName) };
            }
            else
            {
                if (!filterContext.HttpContext.Request.RequestType.Equals(_httpVerbs.ToString(), System.StringComparison.OrdinalIgnoreCase))
                {
                    filterContext.Result = new ContentResult { Content = "方法 {0} 必须是 {1} 方式的Ajax请求才能访问!".With(actionName, _httpVerbs.ToString().ToLower()) };
                }
            }
        }
    }
}
